package 笔试;

import java.util.Stack;

public class 字符串算数转换 {
    private int state = 0;
    public String computeString (String str) {
        // write code here
        Stack<Integer> shuzi = new Stack<>();
        Stack<Character> chenghao = new Stack<>();
        Stack<Character> kuohao = new Stack<>();
        Stack<String> zimu = new Stack<>();

        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) <='9' && str.charAt(i) >= '0') {
                if(state == 0 && !shuzi.isEmpty()) {
                    int t = shuzi.pop();
                    t = t * 10 + str.charAt(i) - '0';
                    shuzi.push(t);
                } else {
                    shuzi.push(str.charAt(i) - '0');
                }
                state = 0;
            } else if(str.charAt(i) == '*') {
                state = 1;
                chenghao.push(str.charAt(i));
            } else if(str.charAt(i) <= 'z' && str.charAt(i) >= 'a') {
                if(state == 3 && !zimu.isEmpty()) {
                    String t = zimu.pop();
                    t = t + str.charAt(i);
                    zimu.push(t);
                } else {
                    String t = "";
                    t += str.charAt(i);
                    zimu.push(t);
                }
                state = 3;
            } else if(str.charAt(i) == '[') {
                kuohao.push(str.charAt(i));
                state = 2;
            } else if(str.charAt(i) == ']') {
                kuohao.pop();
                chenghao.pop();
                int t = shuzi.pop();
                String s = zimu.pop();
                String res = "";
                for(int j = 0; j < t; j++) {
                    res += s;
                }
                if(zimu.isEmpty()) {
                    zimu.push(res);
                } else {
                    String p = zimu.pop();
                    p += res;
                    zimu.push(p);
                }
            }
        }
        return zimu.pop();
    }
}
